import 'package:agora_rtc_engine/agora_rtc_engine.dart';
import 'package:gameplay_flutter/m_rtc/rtc_live_strategy.dart';

class AgoraRtcStrategy implements RtcLiveStrategy {
  final String appId = '86b2ac3562e343f5af1acd303e188c6c';

  late RtcEngine _engine;

  /// 初始化 Agora SDK
  @override
  Future<void> initializeSdk() async {
    // 创建 RtcEngine 对象
    _engine = createAgoraRtcEngine();

    // 初始化 RtcEngine，设置频道场景为 channelProfileLiveBroadcasting（直播场景）
    await _engine.initialize(RtcEngineContext(
      appId: appId,
      channelProfile: ChannelProfileType.channelProfileLiveBroadcasting,
    ));

    // 启用音频功能，禁用视频功能
    await _engine.enableAudio();
    await _engine.disableVideo();
  }

  /// 加入频道
  @override
  Future<void> joinChannel(String channelId, String token) async {
    await _engine.joinChannel(
      token: token,
      channelId: channelId,
      uid: 0,
      options: const ChannelMediaOptions(
        autoSubscribeAudio: true,
        autoSubscribeVideo: false,
        publishMicrophoneTrack: false,
        publishCameraTrack: false,
        enableAudioRecordingOrPlayout: false,
      ),
    );
    await _engine.muteAllRemoteAudioStreams(true);
  }

  /// 开启音频采集
  @override
  Future<void> startAudioCapture() async {
    await _engine.enableLocalAudio(true);
  }

  /// 关闭音频采集
  @override
  Future<void> stopAudioCapture() async {
    await _engine.enableLocalAudio(false);
  }

  /// 切换身份
  @override
  Future<void> switchRole(bool isRoleBroadcaster) async {
    await _engine.setClientRole(
        role: isRoleBroadcaster
            ? ClientRoleType.clientRoleBroadcaster
            : ClientRoleType.clientRoleAudience);
    await _engine.muteLocalAudioStream(isRoleBroadcaster);
  }

  /// 添加混音
  @override
  Future<void> addAudioMixing(String filePath) {
    // TODO: implement addAudioMixing
    throw UnimplementedError();
  }

  /// 移除混音
  @override
  Future<void> removeAudioMixing() {
    // TODO: implement removeAudioMixing
    throw UnimplementedError();
  }

  /// 离开频道
  @override
  Future<void> leaveChannel() async {
    await _engine.leaveChannel();
  }

  /// 释放资源
  @override
  Future<void> dispose() async {
    // 离开频道
    await _engine.release();
  }
}
